﻿
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using Confcloud.Email.Templates;
using Smarly.Core;
using Smarly.Core.Database;

namespace Smarly.Bussines.Model.Subscription
{
	public class Subscriber : ModelStateObject
	{
		[DatabaseValidation("IncorrectCode", "Значение кода не корректно")]
		public string ActivationCode { get; set; }

		[RegularExpression(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$", ErrorMessage = "Значение email не корректно")]
		[DatabaseValidation("EmailExists", "Вы уже подписаны на рассылку")]
		[DatabaseValidation("EmailNotExist", "Вы не являетесь подписчиком на рассылку")]
		[Required]
		public string Email { get; set; }

		public Subscriber Post(string unsubscribeUrl)
		{
			if (ModelState.IsValid)
			{
				SqlRepository.ExecuteProcedureReader("Subscriber_Create",
				                                     new List<SpParam>
					                                     {
						                                     new SpParam {Name = "@email", Type = DbType.String, Value = Email},
					                                     },
				                                     OnSqlInfoMessage,
				                                     reader =>
					                                     {
						                                     while (reader.Read())
						                                     {
																									 ActivationCode = reader.GetString("ActivationCode");
																									 Email = reader.GetString("Email");
						                                     }

						                                     return this;
					                                     });

			}

			if (ModelState.IsValid)
			{
				new SubscribeUserEmail(Email, unsubscribeUrl.Replace("SUBSCRIBEREMAIL", Email).Replace("ACTIVATIONCODE", ActivationCode)).Post();
			}

			return this;
		}

		public Subscriber Delete()
		{

			SqlRepository.ExecuteProcedureReader("Subscriber_Delete",
																					 new List<SpParam>
			                                     	{
			                                     		new SpParam {Name = "@email", Type = DbType.String, Value = Email},
			                                     		new SpParam {Name = "@activationCode", Type = DbType.String, Value = ActivationCode},
			                                     	},
																					 OnSqlInfoMessage,
																					 reader => this);

			if (ModelState.IsValid)
			{
				new UnsubscribeUserEmail(Email).Post();
			}

			return this;
		}
	}
}